package com.horizon.cloud.distribute.IdGenerator.impl;

import com.horizon.cloud.distribute.zookeeper.CuratorZKClient;
import lombok.Data;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;

@Data
public class SnowflakeIdWorker {
    //Zk客户端
    private CuratorFramework client = null;

    //工作节点的路径
    private String pathPrefix = "/test/IDMaker/worker-";
    private String pathRegistered = null;
    private  boolean inited=false;

    public SnowflakeIdWorker() {
        client = CuratorZKClient.getSingletonInstance().getClient();
    }

    /**
     * 定制化的ephemeral_sequential前缀
     * @param type
     */
    public SnowflakeIdWorker(String type) {
        pathPrefix = "/snowflakeId/" + type+"/worker-";
    }

    //在zk中创建临时节点写入信息
    public void init() {
        try {
            client = CuratorZKClient.getSingletonInstance().getClient();
            pathRegistered = client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                    .forPath(pathPrefix);
        } catch (Exception e) {
            e.printStackTrace();
        }

        inited = true;
    }

    public long getId() {
        if(!inited) {
            init();
        }
        String sid = null;
        if (null == pathRegistered) {
            throw new RuntimeException("节点注册失败");
        }

        int index = pathRegistered.lastIndexOf(pathPrefix);
        if (index >= 0) {
            index +=pathPrefix.length();
            sid = index <= pathRegistered.length()? pathRegistered.substring(index)
                    :null;
        }
        if (null == sid) {
            throw new RuntimeException("节点id生成失败");
        }
        return Long.parseLong(sid);
    }
}
